//
//  FirstAuditingTransferOfFundsVC.m
//  优学荟管理系统
//
//  Created by 星道 on 17/7/11.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "FirstAuditingTransferOfFundsVC.h"
#import "FirstAuditingModel.h"
#import "FirstAuditingTransferOfFundsCell.h"
#import "FirstAuditingSearchView.h"
#import "FirstAuditingDetailListVC.h"
@interface FirstAuditingTransferOfFundsVC ()
/**
 当前页码
 */
@property (nonatomic, assign) NSInteger CurrentPage;
/**
 临时页码
 */
@property (nonatomic, assign) NSInteger TempPage;
/**
 数据存放
 */
@property (nonatomic, strong) NSMutableArray *DataArr;
/**
 默认是-1，代表搜索全部
 */
@property (nonatomic, assign) NSInteger OrganizationId;
@end

@implementation FirstAuditingTransferOfFundsVC


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.OrganizationId = -1;

    // 配置TableView
    [self SetupTableView];

}



#pragma mark  - 配置
/**
 配置TableView
 */
- (void)SetupTableView
{
    // 占位
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [UIView new];
    // 预注册
    [self.tableView registerNib:[UINib nibWithNibName:[FirstAuditingTransferOfFundsCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    // 预估高度
    self.tableView.rowHeight = 180;
    //默认页码
    self.CurrentPage = 1;
    //默认ID
    self.OrganizationId = -1;
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        //取当前页码给临时页码
        self.TempPage = self.CurrentPage;
        //设当前页码为1
        self.CurrentPage = 1;
        //请求
        [self RefreshData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        //请求
        [self RefreshData];
    }];
    //开始刷新
    [self.tableView.mj_header beginRefreshing];
}


/**
 刷新失败时，判断是否需要从临时页码里取出来给当前页码
 */
- (void)GetPage
{
    if (self.CurrentPage == 1)
    {
        self.CurrentPage = self.TempPage;
    }
}

/**
 结束刷新

 @param Index 0:结束刷新 1:提示没有更多数据 2:tableView数据源更新
 */
- (void)EndRefresh:(NSInteger)Index;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (Index)
        {
            case 0:
            {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
                break;
            case 1:
            {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
                break;
            case 2:
            {
                [self.tableView reloadData];
            }
                break;
            default:
                break;
        }
    });
}



#pragma mark - 网络请求
/**
 网络请求
 */
- (void)RefreshData
{

    NSDictionary *Params = @{
                             @"action"          :[self GetAction],
                             @"organizationId"  :@(self.OrganizationId),
                             @"pageNumber"      :@(self.CurrentPage)
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {

        //结束刷新
        [self EndRefresh:0];
        //判断是否加载成功
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {

            NSArray *Arr = Obj[@"t"][@"dataList"];
            // 判断是否为空，为空的话显示没有数据了
            if (Arr.count == 0)
            {
                [self EndRefresh:1];
            }
            else
            {
                // 清空数据
                if (self.CurrentPage == 1)
                {
                    [self.DataArr removeAllObjects];
                }
                // 转对象
                [Arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                    FirstAuditingModel *Model = [FirstAuditingModel HNObjectValuesForKey:(NSDictionary *)obj];
                    [self.DataArr addObject:Model];
                }];


                //数据请求成功，页码加1
                self.CurrentPage += 1;
                // 通知刷新
                [self EndRefresh:2];
            }
        }
        else
        {
            //页码处理
            [self GetPage];
            //显示错误信息
            [MBProgressHUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {

        //结束刷新
        [self EndRefresh:0];
        //页码处理
        [self GetPage];
        //显示错误信息
        [MBProgressHUD showError:NetErr];
    }];
}


/**
 根据枚举返回Action
 */
- (NSString *)GetAction
{
    // 资金提现
    if (self.FirstAuditingTransferOfFundsType == FirstAuditingDetailListMoney)
    {
        return @"pendingTransfer";
    }
    // 星币提现
    else if (self.FirstAuditingTransferOfFundsType == FirstAuditingDetailListCoins)
    {
        return @"pendingTransferCoins";
        
    }else if (self.FirstAuditingTransferOfFundsType == FirstAuditingTransferOfFundsTaocan){//套餐提现
        
        
        return @"pendingTransferPackage";
        
    }

    else
    {
        return @"未知";
    }
}


/**
 对设置已提现发起网络请求
 */
- (void)RefreshDataForSetGetMoneyHasBeenWithWithdrawId:(NSString *)WithdrawId
{
    [HUD showHUD];
    // 创建参数
    NSDictionary *Dict = @{
                           @"action"    :[self GetActionForSetGetMoney],
                           @"withdrawId":WithdrawId
                           };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Dict Success:^(id Obj) {

        [HUD showError:Obj[@"msg"]];
        // 成功设置
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            // 1.5秒开始表单刷新
            [self performSelector:@selector(MgrSuccessRefreshTableViewWithWithdrawId:) withObject:WithdrawId afterDelay:1.5];
        }
    } Fail:^(NSError *Error) {
        // 链接失败
        [HUD showError:NetErr];
    }];
}


/**
 根据枚举返回Action
 */
- (NSString *)GetActionForSetGetMoney
{
    // 资金提现
    if (self.FirstAuditingTransferOfFundsType == FirstAuditingDetailListMoney)
    {
        return @"transfer";
    }
    // 星币提现
    else if (self.FirstAuditingTransferOfFundsType == FirstAuditingDetailListCoins)
    {
        return @"transferCoins";
    }else if (self.FirstAuditingTransferOfFundsType == FirstAuditingTransferOfFundsTaocan){
        
        
        return @"transferPackage";
    }

    else
    {
        return @"未知";
    }
}


#pragma mark - TableView代理
//区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.DataArr.count;
}

//Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取出对象
    FirstAuditingModel *Model = self.DataArr[indexPath.row];
    // 实例Cell
    FirstAuditingTransferOfFundsCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    // 点语法
    Cell.Model = Model;
    // 点击按钮事件
    Cell.ClickButton = ^(UIButton *Button)
    {
        // 处理点击事件
        [self MgrCellClick:Button Model:Model];
    };
    return Cell;
}

// 头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [FirstAuditingSearchView ConfigSearchViewWithSearchResult:^(NSString *Str) {
        // 开始搜索啦
        // 页码为1
        self.CurrentPage = 1;
        // 清空数据源
        [self.DataArr removeAllObjects];
        // 动画刷新下界面
        [self.tableView reloadSections:[[NSIndexSet alloc] initWithIndex:0] withRowAnimation:(UITableViewRowAnimationAutomatic)];
        // 得到机构ID
        self.OrganizationId = [Str integerValue];
        // 开始刷新
        [self.tableView.mj_header beginRefreshing];
    }];
}

// 头部视图的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}


#pragma mark - 处理点击事件
/**
 Button.tag:1101设为已提现 1102查看详情
 */
- (void)MgrCellClick:(UIButton *)Button Model:(FirstAuditingModel *)Model
{
    // 已提现
    if (Button.tag == 1101)
    {
        [self MgrSetGetMoneyHasBeenModel:Model];
    }

    // 查看详情
    if (Button.tag == 1102)
    {
        // 实例详情
        FirstAuditingDetailListVC *VC = [[FirstAuditingDetailListVC alloc] init];
        // 传值
        VC.withdrawNo = Model.withdrawNo;
        
        
        if (self.FirstAuditingTransferOfFundsType == FirstAuditingTransferOfFundsMoney) {
            
            VC.FirstAuditingDetailListType = FirstAuditingTransferOfFundsMoney;
        }else if (self.FirstAuditingTransferOfFundsType == FirstAuditingTransferOfFundsCoins){
            
            VC.FirstAuditingDetailListType = FirstAuditingTransferOfFundsCoins;
        }else if (self.FirstAuditingTransferOfFundsType == FirstAuditingTransferOfFundsTaocan){
            
            VC.FirstAuditingDetailListType = FirstAuditingTransferOfFundsTaocan;
            
        }
        
        
//        // 身份
//        VC.FirstAuditingDetailListType = self.FirstAuditingTransferOfFundsType == FirstAuditingTransferOfFundsMoney?FirstAuditingDetailListMoney:FirstAuditingDetailListCoins;
        // 跳转
        [self.navigationController pushViewController:VC animated:YES];
    }
}

/**
 设置已提现
 */
- (void)MgrSetGetMoneyHasBeenModel:(FirstAuditingModel *)Model
{
    // 打开提示
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确认已经对该机构的提现申请进行相应的操作了吗?" preferredStyle:(UIAlertControllerStyleActionSheet)];
    [Alert addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {

        // 请求
        [self RefreshDataForSetGetMoneyHasBeenWithWithdrawId:[Model.withdrawId stringValue]];
    }]];
    [Alert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:Alert animated:YES completion:nil];
}

/**
 设置已提现成功之后，刷新表单
 */
- (void)MgrSuccessRefreshTableViewWithWithdrawId:(NSString *)withdrawId
{
    // 找出该ID相同的对象
    __block FirstAuditingModel *TempModel = nil;
    [self.DataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // 强转
        FirstAuditingModel *Model = (FirstAuditingModel *)obj;
        // 匹配
        if ([[Model.withdrawId stringValue] isEqualToString:withdrawId])
        {
            // 存储
            TempModel = Model;
            // 停止
            *stop = YES;
        }
    }];
    // 得到下标，来做相应的刷新动画
    NSInteger Index = [self.DataArr indexOfObject:TempModel];
    // 移除
    [self.DataArr removeObjectAtIndex:Index];
    // 刷新
    [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:Index inSection:0]] withRowAnimation:(UITableViewRowAnimationAutomatic)];
    [self.tableView endUpdates];
}

#pragma mark - Setter
- (NSMutableArray *)DataArr
{
    if (!_DataArr)
    {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}

@end
